package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FeatureRestController")
public class FeatureRestController extends CmiEmaController {

	/**
	 * Create a new Feature entity
	 * 
	 */
	@RequestMapping(value = "/newFeature", method = RequestMethod.POST)
	@ResponseBody
	public Object newFeature(@RequestBody Feature feature) {
		featureService.saveFeature(feature);
		return JSONObject.parse(cmiPsonService.toJsonString(featureDAO.findFeatureByPrimaryKey(feature.getId()), 2));
	}

	@RequestMapping(value = "/restNewFeature", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFeature(@RequestBody String featureJson) {
		Feature feature = new Gson().fromJson(featureJson, Feature.class);
		appendReferences(feature);
		featureService.saveFeature(feature);
		return JSONObject.parse(cmiPsonService.toJsonString(featureDAO.findFeatureByPrimaryKey(feature.getId()), 2));
	}

	@RequestMapping(value = "/saveFeature", method = RequestMethod.PUT)
	@ResponseBody
	public Feature saveFeature(@RequestBody Feature feature) {
		featureService.saveFeature(feature);
		return featureDAO.findFeatureByPrimaryKey(feature.getId());
	}

	@RequestMapping(value = "/restSaveFeature", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFeature(@RequestBody String featureJson) {
		Feature feature = new Gson().fromJson(featureJson, Feature.class);
		appendReferences(feature);
		CmiPsonService cmiPsonService = new CmiPsonService();
		featureService.saveFeature(feature);
		return JSONObject.parse(cmiPsonService.toJsonString(featureDAO.findFeatureByPrimaryKey(feature.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFeature/{featureId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFeature(@PathVariable Integer featureId) {
		Feature feature = featureDAO.findFeatureByPrimaryKey(featureId);
		featureService.deleteFeature(feature);
	}

	@RequestMapping(value = "/restConfirmDeleteFeatures")
	@ResponseBody
	public Object restConfirmDeleteFeatures(@RequestBody Set<Integer> deleteFeaturesIds) {
		Set<Feature> deleteFeatures = featureDAO.findFeaturesByIds(deleteFeaturesIds);
		Set<Feature> referencedFeatures = featureService.loadReferenceFeatures(deleteFeatures);
		deleteFeatures.removeAll(referencedFeatures);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFeatures);
		jsonObject.put("deleteEntitys", deleteFeatures);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFeatures")
	@ResponseBody
	public Object restDeleteFeatures(@RequestBody Set<Feature> deleteFeatures) {
		Iterator<Feature> iterator = deleteFeatures.iterator();
		while (iterator.hasNext()) {
			Feature currentFeature = iterator.next();
			featureService.deleteFeature(currentFeature);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFeatures");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFeature/{featureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeature(@PathVariable Integer featureId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(featureDAO.findFeatureByPrimaryKey(featureId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFeatureDetectmethod/{featureId}/detectmethod", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeatureDetectmethod(@PathVariable Integer featureId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(featureDAO.findFeatureByPrimaryKey(featureId).getDetectmethod(),
				2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadFeatureDetectdetails/{featureId}/detectdetails/{relateddetectdetailId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeatureDetectdetails(@PathVariable Integer featureId,
			@PathVariable Integer relateddetectdetailId, @RequestBody CmiPagination cmiPagination) {
		Detectdetail detectdetail = detectdetailDAO.findDetectdetailByPrimaryKey(relateddetectdetailId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectdetail, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFeatureDetectfeatures/{featureId}/detectfeatures/{relateddetectfeatureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeatureDetectfeatures(@PathVariable Integer featureId,
			@PathVariable Integer relateddetectfeatureId, @RequestBody CmiPagination cmiPagination) {
		Detectfeature detectfeature = detectfeatureDAO.findDetectfeatureByPrimaryKey(relateddetectfeatureId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectfeature, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFeatureDetectstandards/{featureId}/detectstandards/{relateddetectstandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeatureDetectstandards(@PathVariable Integer featureId,
			@PathVariable Integer relateddetectstandardId, @RequestBody CmiPagination cmiPagination) {
		Detectstandard detectstandard = detectstandardDAO.findDetectstandardByPrimaryKey(relateddetectstandardId, -1,
				-1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectstandard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFeatureFeaturestandards/{featureId}/featurestandards/{relatedfeaturestandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeatureFeaturestandards(@PathVariable Integer featureId,
			@PathVariable Integer relatedfeaturestandardId, @RequestBody CmiPagination cmiPagination) {
		Featurestandard featurestandard = featurestandardDAO.findFeaturestandardByPrimaryKey(relatedfeaturestandardId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(featurestandard, 2, cmiPagination));
	}

	public void appendReferences(Feature feature) {

		Detectmethod detectmethod = feature.getDetectmethod();
		if (detectmethod != null)
			feature.setDetectmethod(detectmethodService.findDetectmethodByPrimaryKey(detectmethod.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectdetail> detectdetailsForFeature = new HashSet<>();
		for (Detectdetail detectdetail_Feature : feature.getDetectdetailsForFeature()) {
			detectdetailsForFeature.add(detectdetailService.findDetectdetailByPrimaryKey(detectdetail_Feature.getId()));
		}
		feature.setDetectdetailsForFeature(detectdetailsForFeature);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectfeature> detectfeaturesForFeature = new HashSet<>();
		for (Detectfeature detectfeature_Feature : feature.getDetectfeaturesForFeature()) {
			detectfeaturesForFeature
					.add(detectfeatureService.findDetectfeatureByPrimaryKey(detectfeature_Feature.getId()));
		}
		feature.setDetectfeaturesForFeature(detectfeaturesForFeature);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectstandard> detectstandardsForFeature = new HashSet<>();
		for (Detectstandard detectstandard_Feature : feature.getDetectstandardsForFeature()) {
			detectstandardsForFeature
					.add(detectstandardService.findDetectstandardByPrimaryKey(detectstandard_Feature.getId()));
		}
		feature.setDetectstandardsForFeature(detectstandardsForFeature);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Featurestandard> featurestandardsForFeature = new HashSet<>();
		for (Featurestandard featurestandard_Feature : feature.getFeaturestandardsForFeature()) {
			featurestandardsForFeature
					.add(featurestandardService.findFeaturestandardByPrimaryKey(featurestandard_Feature.getId()));
		}
		feature.setFeaturestandardsForFeature(featurestandardsForFeature);
	}

	@RequestMapping(value = "/restGetFeatureDetectmethod/{featureId}/detectmethod", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFeatureDetectmethod(@PathVariable Integer featureId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(featureDAO.findFeatureByPrimaryKey(featureId).getDetectmethod(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFeatureDetectdetails/{featureId}/detectdetails", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFeatureDetectdetails(@PathVariable Integer featureId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(featureDAO.findFeatureByPrimaryKey(featureId).getDetectdetailsForFeature(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFeatureDetectfeatures/{featureId}/detectfeatures", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFeatureDetectfeatures(@PathVariable Integer featureId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(featureDAO.findFeatureByPrimaryKey(featureId).getDetectfeaturesForFeature(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFeatureDetectstandards/{featureId}/detectstandards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFeatureDetectstandards(@PathVariable Integer featureId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				featureDAO.findFeatureByPrimaryKey(featureId).getDetectstandardsForFeature(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFeatureFeaturestandards/{featureId}/featurestandards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFeatureFeaturestandards(@PathVariable Integer featureId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				featureDAO.findFeatureByPrimaryKey(featureId).getFeaturestandardsForFeature(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListFeatures", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFeatures() {
		return JSONObject.parse(cmiPsonService.toJsonString(featureService.loadFeatures(), 2));
	}

	@RequestMapping(value = "/restListFeaturesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFeaturesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = featurePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Feature> features = featureDAO.findAllFeatures(startResult, cmiPagination.getPaginationSize());
		String featureString = cmiPsonService.toPsonString(features, 2, cmiPagination);

		return JSONObject.parse(featureString);
	}

	@RequestMapping("/featureSelectBox")
	@ResponseBody
	public JSONObject featureSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Detectmethod":
				entitySet = detectmethodService.loadDetectmethodsByIdSet(searchValue);
				break;

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailService.loadDetectdetailsByIdSet(searchValue);
				break;
			case "Detectfeature":
				entitySet = detectfeatureService.loadDetectfeaturesByIdSet(searchValue);
				break;
			case "Detectstandard":
				entitySet = detectstandardService.loadDetectstandardsByIdSet(searchValue);
				break;
			case "Featurestandard":
				entitySet = featurestandardService.loadFeaturestandardsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Detectmethod":
				entitySet = detectmethodDAO.findAllDetectmethods((pageNumber - 1) * paginationSize, paginationSize);
				count = detectmethodService.countDetectmethods();
				break;

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailDAO.findAllDetectdetails((pageNumber - 1) * paginationSize, paginationSize);
				count = detectdetailService.countDetectdetails();
				break;
			case "Detectfeature":
				entitySet = detectfeatureDAO.findAllDetectfeatures((pageNumber - 1) * paginationSize, paginationSize);
				count = detectfeatureService.countDetectfeatures();
				break;
			case "Detectstandard":
				entitySet = detectstandardDAO.findAllDetectstandards((pageNumber - 1) * paginationSize, paginationSize);
				count = detectstandardService.countDetectstandards();
				break;
			case "Featurestandard":
				entitySet = featurestandardDAO.findAllFeaturestandards((pageNumber - 1) * paginationSize,
						paginationSize);
				count = featurestandardService.countFeaturestandards();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Detectmethod":
				entitySet = detectmethodDAO.findDetectmethodByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectmethodService.countDetectmethodsByName(queryword);
				break;

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailDAO.findDetectdetailByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectdetailService.countDetectdetailsByName(queryword);
				break;
			case "Detectfeature":
				entitySet = detectfeatureDAO.findDetectfeatureByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectfeatureService.countDetectfeaturesByName(queryword);
				break;
			case "Detectstandard":
				entitySet = detectstandardDAO.findDetectstandardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectstandardService.countDetectstandardsByName(queryword);
				break;
			case "Featurestandard":
				entitySet = featurestandardDAO.findFeaturestandardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = featurestandardService.countFeaturestandardsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
